<?php 
$page_title = "21 Game - Challenge player";
include("header.php");
if(!isset($_SESSION['username'])){
	header("Location: index.php");
}
 ?>

<!-- page header -->
<div class="page-header">
	<div class="container">
		<h1>Challenge player</h1>
	</div>
</div>
<!-- end page header -->

<div class="container">
	<?php 
		require_once("sql/connection.php");
		require_once("utilities/functions.php");

	if(isset($_GET['nickname']) AND isset($_GET['coins'])){
		$nickname = $_GET['nickname'];
		$coins = $_GET['coins'];
			if(isset($_POST['cSubmited']) AND $_POST['cSubmited'] == "Submit"){

				$bet = $_POST['bet'];
				challengePlayer($dbc, $nickname,$bet,$_SESSION['username']);
			}
			else{
			echo "<div class='row'>
			<p class='lead'>You want to challenge <b>$nickname</b>. He/She has <b>$coins</b> coins.</p>
			<div class='col-lg-3'>
			<form action='' method='POST'>
			<div class='form-group'>
				<label for='bet'>Place your bet</label>
				<input type='text' name='bet' class='form-control' placeholder='Bet'>
			</div>
			<input type='submit' name='cSubmited' value='Submit' style='background:red' class='btn btn-primary btn-block'>
			</form>
			<h5 class='text-muted'>You can't bet more coins than your opponent has.</h5>
			</div>
			</div>";
		}
	}
	else{
		//List all the players besides you.
		$query = "SELECT nickname, coins FROM Players WHERE nickname != '{$_SESSION['username']}' ORDER BY coins DESC";
		$r = mysqli_query($dbc,$query);

		//Show a table with all the players only if there are players to challenge
		if(mysqli_num_rows($r) > 0){
			echo "<div class='col-lg-6'>
				<table class='table table-hover'>
				<tr><th>Nickname</th><th>Coins</th><td></td></tr>";

			while($data = mysqli_fetch_array($r,MYSQLI_ASSOC)){
				if(checkMatch($dbc, $_SESSION['username'], $data['nickname'])){
					$disabled = "1";
				}
				else{
					$disabled = "0";
				}

				echo "
				<tr><td>".$data['nickname']."</td><td>".$data['coins']."</td><td><a class='btn btn-primary btn-block' style='background:red' ".(($disabled == "1") ? 'disabled="disabled"': '')." href='challenge.php?&nickname={$data['nickname']}&coins={$data['coins']}'>Challenge</a></td></tr>";
			}

			echo "</table>				
				  </div>";
		}
		else{
			echo "<p>There are no players to challenge.</p>";
		}
	} 
	 ?>
</div>

<?php include("footer.php"); ?>